<template>
    <div class="page-wrap version-control-wrap">
        <sys-set @success="sysSetChange" :defaultSystem="system" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <a-divider class="full-divider-h" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <flexbox justify="space-between" align="flex-start" class="table-toolbar-wrap">
            <filter-form @search="handleSearch" v-show="!selectedKeys.length" />
            <flexbox align="center" class="margin-l-16" v-show="selectedKeys.length">
                <span class="margin-r-16">
                    已选中<a>{{ selectedKeys.length }}</a> 项
                </span>
                <a-button type="primary" @click="handleOneVersion"> 导出日志 </a-button>
            </flexbox>
            <flexbox justify="flex-end" class="margin-l-16">
                <a-button type="primary" class="margin-r-16" @click="handleCreate" v-auth="'version.versionList.createVersion'">
                    新建预发布版本
                </a-button>
                <a-tooltip title="表格列配置">
                    <column-setting :columns="settingColumns" @setColumns="setColumns" />
                </a-tooltip>
            </flexbox>
        </flexbox>

        <custom-table
            autoResize
            rowKey="id"
            size="small"
            :loading="loading"
            :columns="tableColumns"
            :data-source="list"
            :pagination="paginationConfig"
            :expandIcon="handleExpandIcon"
            @change="handleTableChange"
        >
            <template #radio="{ record }" v-if="userInfo.roles.includes('产品经理')">
                <a-radio :value="record.id" :checked="selectedKeys.includes(record.id)" @click.stop="handleRadioChange" />
            </template>
            <template #status="{ record }">
                <h-status-badge :status="record.status" type="version" />
            </template>
            <template #versionName="{ record }">
                <a @click="showDetail(record.id)" v-copyText="record.versionName">{{ record.versionName }}</a>
                <a-tag v-if="record.requireChange === 0" color="orange" class="margin-l-8">需求变更</a-tag>
            </template>
            <template #processStatus="{ record }">
                {{ $filters.valToNameFilter('processStatus', record.processStatus) }}
            </template>
            <template #jiraId="{ record }">
                {{ record.jiraId ? 'JIRA' : '' }}
            </template>
            <template #expectTime="{ record }">
                {{ $filters.dateFilter(record.expectTime) }}
            </template>
            <template #startTime="{ record }">
                {{ $filters.dateFilter(record.startTime) }}
            </template>
            <template #onlineRealTime="{ record }">
                {{ $filters.dateFilter(record.onlineRealTime) }}
            </template>
            <template #system="{ record }">
                {{ $filters.valToNameFilter('fromSystem', record.system) }}
            </template>
            <!-- 嵌套产品需求表格 -->
            <template v-slot:expandedRowRender="{ record }">
                <!-- jira issue -->
                <a-table
                    rowKey="id"
                    size="small"
                    :columns="productTableColumns"
                    :data-source="record.pmpProductRequires"
                    :pagination="false"
                    v-if="record.jiraId"
                >
                    <template #verOrder="{ index }">
                        {{ index + 1 }}
                    </template>
                    <template #title>
                        <span class="font-w-b">产品需求列表</span>
                    </template>
                    <template #requireName="{ record }">
                        <router-link :to="{ path: '/productRequire/productDetail', query: { id: record.id } }">
                            <span v-copyText="record.requireName">{{ record.requireName }}</span>
                        </router-link>
                    </template>
                    <template #jiraUrl="{ record }">
                        <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">{{ $filters.jiraUrlFilter(record.jiraUrl) }}</a>
                    </template>
                    <template #requireType="{ record }">
                        <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
                    </template>
                    <template #level="{ record }">
                        <h-level :level="record.level" v-if="record.level" />
                    </template>
                    <template #action="{ record }">
                        <router-link :to="{ path: '/productRequire/productDetail', query: { id: record.id } }">详情</router-link>
                    </template>
                </a-table>
                <!-- 用来显示jira版本绑定jira issue列表的需求 -->
                <a-table
                    rowKey="id"
                    size="small"
                    :columns="jiraIssueTableColumns"
                    :data-source="record.pmpJiraIssueDTOs"
                    :pagination="false"
                    v-else-if="record.pmpProductDetailDTO.isOutsideSystem === '1'"
                >
                    <template #verOrder="{ index }">
                        {{ index + 1 }}
                    </template>
                    <template #title>
                        <span class="font-w-b">产品需求列表</span>
                    </template>
                    <template #summary="{ text }">
                        {{ text }}
                    </template>
                    <template #requireType="{ record }">
                        <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
                    </template>
                    <template #action="{ record }">
                        <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">详情</a>
                    </template>
                </a-table>
                <!-- 非jira issue -->
                <a-table rowKey="id" size="small" :columns="productTableColumns" :data-source="record.pmpProductRequires" :pagination="false" v-else>
                    <template #verOrder="{ index }">
                        {{ index + 1 }}
                    </template>
                    <template #title>
                        <span class="font-w-b">产品需求列表</span>
                    </template>
                    <template #requireName="{ record }">
                        <router-link :to="{ path: '/productRequire/productDetail', query: { id: record.id } }">
                            <span v-copyText="record.requireName">{{ record.requireName }}</span>
                        </router-link>
                    </template>
                    <template #jiraUrl="{ record }">
                        <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">{{ $filters.jiraUrlFilter(record.jiraUrl) }}</a>
                    </template>
                    <template #requireType="{ record }">
                        <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
                    </template>
                    <template #level="{ record }">
                        <h-level :level="record.level" v-if="record.level" />
                    </template>
                    <template #action="{ record }">
                        <router-link :to="{ path: '/productRequire/productDetail', query: { id: record.id } }">详情</router-link>
                    </template>
                </a-table>
            </template>
            <template #action="{ record }">
                <table-action :record="record" @actionEvent="handleMenuEvent" />
            </template>
        </custom-table>
        <create-version ref="createVersionRef" @success="getList" />
        <relative-change-table ref="relativeChangeTableRef" />
    </div>
</template>

<script lang="ts">
import store from '@/store';
import { useMessage } from '@/hooks/common/useMessage';
import { message } from 'ant-design-vue/es';
import CreateVersion from './components/CreateVersion.vue';
import TableAction from './components/TableAction.vue';
import FilterForm from './components/FilterForm.vue';
import { SysSet, HLevel, HProductType, HStatusBadge, CustomTable, ColumnSetting } from '@/components';
import RelativeChangeTable from '@/components/Content/RelativeChangeTable.vue';
import { useMountedAndActivated } from '@/hooks/common/useMountedAndActivated';
import { useTableData, useTableLoading, usePagination, useTableColumns, useTableFormSearch, useTableAction } from '@/components/Table/hooks/index';
import { expandIcon } from '@/utils/renderCustomFn.tsx';
import { useRouter, useRoute } from 'vue-router';
import { useJira } from '@/hooks/content/useJira';
import { productTableColumns, jiraIssueTableColumns } from './config/columns';
import api from '@/api';
import { downByBlob } from '@/utils/file/downFile';
import { defineComponent, ref, unref, toRefs, reactive, h } from 'vue';
export default defineComponent({
    components: {
        CreateVersion,
        SysSet,
        HLevel,
        HProductType,
        HStatusBadge,
        RelativeChangeTable,
        TableAction,
        FilterForm,
        CustomTable,
        ColumnSetting
    },
    setup() {
        const router = useRouter();
        const route = useRoute();
        const createVersionRef = ref();
        const relativeChangeTableRef = ref();
        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const { columns: tableColumns, setColumns, settingColumns } = useTableColumns('version');
        const { list, getList, handleTableChange, setSearchQuery } = useTableData(setLoading, paginationConfig, setPaginationConfig, 'version');
        const { handleSearch } = useTableFormSearch(setPaginationConfig, setSearchQuery, getList);
        const { showDetail } = useTableAction('version', getList, relativeChangeTableRef);

        const state = reactive<any>({
            system: null,
            selectedStatusValue: '',
            selectedKeys: []
        });
        const { createConfirm } = useMessage();
        // 创建版本
        const handleCreate = () => {
            createVersionRef.value.open(state.system);
        };

        // 自定义系统回调
        const sysSetChange = (checkedSystem: number, systemInfo = {}, catalogType = null) => {
            state.selectedKeys = [];
            setPaginationConfig({
                current: 1
            });
            // 如果传入catalogType，及左侧树模式
            if (catalogType !== null) {
                setSearchQuery({
                    catalogCode: checkedSystem,
                    catalogType
                });
            } else {
                // checkLogin(checkedSystem);
                setSearchQuery({
                    system: checkedSystem,
                    admin: store.getters.userInfo.roles.some((item) => ['admin', '观察者', '领导', '产品管理委员会'].includes(item)) ? 1 : 0
                });
                state.system = checkedSystem;
            }
            getList();
        };
        // 动态控制展开图标
        const handleExpandIcon = (props) => {
            // 从外部引入，是因为内部不支持jsx
            return expandIcon(props, 'pmpProductRequires') || expandIcon(props, 'pmpJiraIssueDTOs');
        };
        const handleReplenish = (id) => {
            router.push({
                path: '/productRequire/createVersionReplenish',
                query: {
                    id
                }
            });
        };
        const handleRadioChange = (e) => {
            if (state.selectedKeys.length) {
                state.selectedKeys = state.selectedKeys[0] === +e.target.value ? [] : [+e.target.value];
            } else {
                state.selectedKeys = [+e.target.value];
            }
        };
        const handleOneVersion = async () => {
            const target = unref(list).find((item) => item.id === state.selectedKeys[0]);
            if (target) {
                const query = {
                    ...target
                };
                const res = await api.fileModel.exportVersion(query, {
                    responseType: 'blob'
                });
                downByBlob(res, target.versionName + '.xls');
            }
        };
        // 操作回调
        const handleMenuEvent = async ({ type, record }) => {
            const { id, versionName } = record;
            switch (type) {
                case 'detail':
                    showDetail(id);
                    return;
                case 'delete':
                    if (record.status === '1') {
                        handleDelete(id, versionName);
                    } else {
                        // 产品经理修改节点也可以修改
                        if (record.stage === '6' && record.instanceId) {
                            const moule = await getProcessStatus(record.instanceId);
                            if (moule === 'productChange') {
                                handleDelete(id, versionName);
                            } else {
                                message.error('该流程下不能删除');
                            }
                        } else {
                            message.error('该流程下不能删除');
                        }
                    }
                    return;
                case 'replenish':
                    handleReplenish(id);
                    return;
            }
        };
        const jumpTo = (link) => {
            window.open(link, '_blank');
        };
        const getProcessStatus = async (instanceId: string) => {
            const query = {
                instanceId
            };
            const { success, moule } = await api.productProcessModel.processStatus(query);
            if (success) {
                return moule;
            }
        };
        setSearchQuery({
            status: ''
        });
        // 删除
        const handleDelete = async (id: number, title: string) => {
            const { success, moule } = await api.versionModel.findById({
                id
            });
            if (success) {
                createConfirm({
                    title: `确认删除【${title}】?`,
                    iconType: 'danger',
                    onOk: async () => {
                        const query = {
                            id
                        };
                        const { success, errorMsg } = await api.versionModel.deleteById(query);
                        if (success) {
                            message.success('删除成功');
                            if (moule.delVmtId) {
                                createConfirm({
                                    title: `确认是否删除【${title}】及对应的版本号?`,
                                    iconType: 'danger',
                                    onOk: async () => {
                                        const query = {
                                            id: moule.delVmtId
                                        };
                                        const { success, errorMsg } = await api.versionControlModel.delete(query);
                                        if (success) {
                                            message.success('删除成功');
                                            getList && getList();
                                        } else {
                                            message.error(errorMsg);
                                        }
                                    },
                                    onCancel: () => {
                                        getList && getList();
                                    }
                                });
                            } else {
                                getList && getList();
                            }
                        } else {
                            message.error(errorMsg);
                        }
                    }
                });
            }
        };
        useMountedAndActivated(getList, false);
        if (route.query.systemId) {
            state.system = route.query.systemId;
        }
        return {
            ...toRefs(state),
            loading,
            list,
            tableColumns,
            settingColumns,
            paginationConfig,
            createVersionRef,
            relativeChangeTableRef,
            productTableColumns,
            jiraIssueTableColumns,
            handleTableChange,
            sysSetChange,
            handleCreate,
            handleMenuEvent,
            handleExpandIcon,
            getList,
            handleDelete,
            showDetail,
            handleSearch,
            handleRadioChange,
            handleOneVersion,
            setColumns,
            jumpTo
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    min-height: 100%;
    padding: 8px 24px 12px 24px;
    background: #fff;
    .table-toolbar-wrap {
        margin-bottom: 16px;
        .ant-btn + .ant-btn {
            margin-left: 8px;
        }
    }
    .table-title {
        font-size: 16px;
        font-weight: bold;
    }
}
.version-control-wrap {
    // table的title背景色
    ::v-deep(.ant-table-title) {
        background: #f8f8f9;
    }
}
</style>